package com.homedo.microservice.distributed.id.service.service;

import com.homedo.common.dao.autoconfig.DbConfig;
import com.homedo.common.dao.conf.DbConf;
import com.homedo.microservice.distributed.id.service.conf.GenerateIdConf;
import com.homedo.microservice.distributed.id.service.exception.InitException;
import com.sankuai.inf.leaf.IDGen;
import com.sankuai.inf.leaf.common.Result;
import com.sankuai.inf.leaf.common.ZeroIDGen;
import com.sankuai.inf.leaf.segment.SegmentIDGenImpl;
import com.sankuai.inf.leaf.segment.dao.IDAllocDao;
import com.sankuai.inf.leaf.segment.dao.impl.IDAllocDaoImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;

@Service
public class SegmentService implements InitializingBean {
    @Autowired
    private GenerateIdConf generateIdConf;

    private Logger logger = LoggerFactory.getLogger(SegmentService.class);
    private IDGen idGen;

    @Override
    public void afterPropertiesSet() throws Exception {

        boolean flag = generateIdConf.isEnable();

        if (flag) {
            // Config dataSource
            DataSource dataSource = DbConf.getInstance().getDefaultDataSource().get(DbConfig.DEAFULT_DATA_SOURCE_NAME);

            // Config Dao
            IDAllocDao dao = new IDAllocDaoImpl(dataSource);

            // Config ID Gen
            idGen = new SegmentIDGenImpl();
            ((SegmentIDGenImpl) idGen).setDao(dao);
            if (idGen.init()) {
                logger.info("Segment Service Init Successfully");
            } else {
                throw new InitException("Segment Service Init Fail");
            }
        } else {
            idGen = new ZeroIDGen();
            logger.info("Zero ID Gen Service Init Successfully");
        }
    }

    public Result getId(String key) {
        return idGen.get(key);
    }

    public SegmentIDGenImpl getIdGen() {
        if (idGen instanceof SegmentIDGenImpl) {
            return (SegmentIDGenImpl) idGen;
        }
        return null;
    }


}
